import store from '@/store'
import {registerMicroApps} from 'qiankun'
import config from '@/utils/config'
import {getDevApp, getDevMenu} from './devPluginConfig'
import { getAccessToken } from "@/utils/auth";
const genActiveRule = hash => location => location.hash.startsWith(hash)
import actions from '@/utils/qiankunActions.js'

export const registerPluginMenu = (pluginWebInfos) => {
  debugger
  if (config.isDev()) {
    // 在开发环境下获取开发环境配置的microApp
    pluginWebInfos = getDevApp()
  }
  var baseUrl = location.protocol + '//' + location.host;
  console.info('微应用注册：' + JSON.stringify(pluginWebInfos));
  console.info('基础路径：' + baseUrl);
  if (pluginWebInfos) {
    const registerMicroApp = []
    const props = getProps()
    console.info('微应用传参数....')
    debugger
    pluginWebInfos.forEach(pluginWebInfo => {
      console.info('注册菜单：' + JSON.stringify(pluginWebInfo));
      registerMicroApp.push({
        name: pluginWebInfo.menuAlias, // app name registered
        entry: baseUrl + pluginWebInfo.menuPath,
        container: '#micro-view',
        activeRule: pluginWebInfo.rootRouting,
        //activeRule: genActiveRule(`#${pluginWebInfo.rootRouting}`),
        props: props
      })
      // 导出的是registerMicroApps的第一个参数，是一个对象数组，其中数组每个字段的作用如下：
      // （1）name：微应用的名称，后面改造微应用的时候一定要与这个name对应,应用名不可重复
      // （2）entry：微应用运行的域名加端口，我用的是本地8088端口,默认加载应用路径(ip与端口)
      // （3）container：启动微应用需要一个dom容器，里面就是这个dom容器的 id
      // （4）activeRule：触发启动微应用的规则，当检测到url中含有activeRule的值时，将启动微应用,激活该应用的路径（子应用路由基地址）
    })
    registerMicroApp.map(app => {
      // 将监听的路由下发到子应用的base
      // 下发路由给子应用，子应用根据该值去定义qiankun环境下的路由
      const routerBase = app.activeRule
      console.info('qiankun 路由：' + routerBase)
      app.props = {
        routerBase,
        store,
        token:getAccessToken(),
        actions
      }
      return app
    });
    registerMicroApps(registerMicroApp, {
      beforeLoad: app => console.log('qiankun beforeLoad ===> ', app.name),
      beforeMount: app => console.log('qiankun beforeMount ===> ', app.name),
      afterMount: app => console.log('qiankun afterMount ===> ', app.name),
      beforeUnmount: app => console.log('qiankun beforeUnmount ===> ', app.name),
      afterUnmount: app => console.log('qiankun afterUnmount ===> ', app.name)
    })
  }
}

export const genDevMenu = () => {
  debugger
  if (config.isDev()) {
    return getDevMenu()
  } else {
    return []
  }
}

const getProps = () => {
  //共享主应用的store实例
  //const props = {actions}
  const props = {}
  //props.token = getAccessToken()
  //props.store = store;
  debugger
  return props
}
